package com.fly.video.downloader.content.history;

import com.fly.video.downloader.App;
import com.fly.video.downloader.bean.Video;
import com.fly.video.downloader.database.HistoryDBHelper;
import ohos.data.rdb.RdbPredicates;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.Date;

public class History {

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "MainAbilitySlice");
    private static RdbStore dbHelper =HistoryDBHelper.getIntance(App.getAppContext());

    public static ArrayList<Video> get(int page, int size)
    {
        ArrayList<Video> videos = new ArrayList<>();
        ResultSet resultSet = dbHelper.querySql("SELECT * FROM "+HistoryDBHelper.DB_NAME+" ORDER BY created_at DESC LIMIT ?, ?", new String[]{((page - 1) * size) + "", size + ""});
        if (resultSet == null || resultSet.getRowCount() == 0) {
            HiLog.info(LABEL_LOG, "query: resultSet is null or no result found");
            return videos;
        }
        resultSet.goToFirstRow();
        do {
            Video video = parseToVideo(resultSet.getString(resultSet.getColumnIndexForName("className")), resultSet.getString(resultSet.getColumnIndexForName("json")));
            if (video != null)
                videos.add(video);{
            }
        }while (resultSet.goToNextRow());
        resultSet.close();
//        dbHelper.close();
        return videos;
    }

    public static <T extends Video> void put(T video)
    {
        ResultSet cursor = dbHelper.querySql("SELECT id FROM "+HistoryDBHelper.DB_NAME+" WHERE vid = ? ", new String[]{video.getId()});
        ValuesBucket values = new ValuesBucket ();
        values.putString("vid", video.getId());
        values.putString("className", video.getClass().getName());
        values.putString("json", video.toJson());
        values.putLong("created_at", new Date().getTime() / 1000);

        if (cursor.goToFirstRow()) // 有， 则更新
        {
            int id = cursor.getInt(0);
            RdbPredicates rdbPredicates=new RdbPredicates(HistoryDBHelper.DB_NAME);
            rdbPredicates.equalTo("id",id);
            dbHelper.update(values,rdbPredicates);
        } else {
            dbHelper.insert(HistoryDBHelper.DB_NAME, values);
        }
        cursor.close();
//        dbHelper.close();
    }

    private static <T extends Video> T parseToVideo(String className, String json)
    {
        try
        {
            Class<? extends Video> clazz = Class.forName(className).asSubclass(Video.class);

            return (T)Video.fromJson(clazz, json);
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
